//
//  LandscapeLiveVC.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2023/11/12.
//

#import "LandscapeLiveVC.h"
#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import "LiveChatViewController.h"
#import "RYAlertController.h"
#import "BottomActionView.h"
#import "EnterTipView.h"
#import "CustomSwitch.h"

// 流状态 String
static NSString *StreamState[] = {
    @"PLStreamStateUnknow",
    @"PLStreamStateConnecting",
    @"PLStreamStateConnected",
    @"PLStreamStateDisconnecting",
    @"PLStreamStateDisconnected",
    @"PLStreamStateAutoReconnecting",
    @"PLStreamStateError"
};
@interface LandscapeLiveVC ()<YouinRTCDelegate,youinRTCChatDelegate,RTCChatVCDelegate,BottomActionDelegate,CustomSwitchDelegate,UITextViewDelegate>
{
    UIView *bgView;
    AppDelegate *appDelegate;
}
@property(nonatomic,strong)YouinRTCManager *manager;
@property(nonatomic,strong)UIImageView *avatar;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UILabel *watchLabel;
@property(nonatomic,strong)UIView *avatarBgView;
@property(nonatomic,strong)UIButton *startBtn;//开始直播
@property(nonatomic,strong)LiveChatViewController *chatTable;
@property (strong, nonatomic) NSTimer *__nullable heatBeat;
@property (assign, nonatomic) NSTimeInterval reConnectTime;
@property(nonatomic,strong)NSTimer *roomStateTimer;
@property(nonatomic,assign)int roomStateSeconds;
@property(nonatomic,copy)NSString *roomId;//房间id
@property(nonatomic,assign)bool isLive;
@property(nonatomic,strong)CourseModel *corseInfoModel;
@property(nonatomic,strong)NSMutableArray *enterTimeArray;
@property(nonatomic,strong)NSMutableArray *enterNameArray;
@property(nonatomic,strong)NSMutableArray *enterTipViews;
@property(nonatomic,strong)UIButton *tap;
@property(nonatomic,strong)BottomActionView *bottomView;
@property(nonatomic,strong)UIView *chatInputView;
@property(nonatomic,strong)UITextView *chatTextView;
@property(nonatomic,strong)UIButton *sendbutton;
@end

@implementation LandscapeLiveVC
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.manager leaveRoom];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    [NSTimer scheduledTimerWithTimeInterval:0.25 repeats:NO block:^(NSTimer * _Nonnull timer) {
        self.chatInputView.hidden = true;
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.roomStateSeconds = 30;
    self.isLive = false;
    self.enterTimeArray = [NSMutableArray array];
    self.enterNameArray = [NSMutableArray array];
    self.enterTipViews = [NSMutableArray array];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.isFlip = true;
    bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH)];
//    bgView.backgroundColor = [UIColor redColor];
    [self.view addSubview:bgView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
//    UIButton *back = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectMake(SCREEN_HEIGHT - 50 - 25,kStatusBarHeight-10, 50, 30) image:[UIImage imageNamed:@"back"] title:nil font:nil backColot:rgba(0, 0, 0, 0.3) textColor:nil target:self action:@selector(backAction) layer:15];
//    [self.view addSubview:back];
    
    [self companyInfo];
    
    [self previewVideo];
    
    //正则截取roomid
    [self getRoomIdWithPulishUrl:self.publishUrl];

    self.tap = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.tap addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:self.tap];
    [self.tap mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.chatTable.view.mas_right).offset(10);
        make.right.mas_equalTo(bgView.mas_right).offset(-70);
        make.bottom.mas_equalTo(self.startBtn.mas_top).offset(-10);
        make.top.mas_equalTo(self.avatarBgView.mas_top);
    }];
}

- (void)companyInfo
{
    self.avatarBgView = [UIView new];
    self.avatarBgView.backgroundColor = rgba(0, 0, 0, 0.4);
    self.avatarBgView.layer.cornerRadius = 22.5;
    self.avatarBgView.layer.masksToBounds = YES;
    [bgView addSubview:self.avatarBgView];
    
    self.titleLabel = [[UIFactory shareInstace] setLabel:CGRectZero text:@"" font:[UIFont systemFontOfSize:12] textColor:[UIColor whiteColor]];
    self.titleLabel.text = @"Youin";
    [self.avatarBgView addSubview:self.titleLabel];
    
    self.watchLabel = [[UIFactory shareInstace] setLabel:CGRectZero text:@"" font:[UIFont systemFontOfSize:10] textColor:[UIColor whiteColor]];
    self.watchLabel.text = @"10次访问";
    [self.avatarBgView addSubview:self.watchLabel];
    
    self.avatar = [UIImageView new];
    self.avatar.layer.cornerRadius = 16.5;
    self.avatar.layer.masksToBounds = YES;
    self.avatar.backgroundColor = [UIColor clearColor];
    self.avatar.image = [UIImage imageNamed:@"people_img"];
//    [self.avatar sd_setImageWithURL:[NSURL URLWithString:@"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F2bf1b169-d217-44c3-a5b3-dd00813bc20d%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1702385805&t=f8d93047f6c2091a9d6a6c2539bad209"]];
    [self.avatarBgView addSubview:self.avatar];
    
    
    [self.avatarBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(bgView).offset(kStatusBarHeight-15);
        make.left.mas_equalTo(bgView).offset(40);
        make.height.mas_equalTo(45);
        make.width.mas_lessThanOrEqualTo(SCREEN_WIDTH-100);
    }];
    
    [self.avatar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.avatarBgView).offset(6);
        make.left.mas_equalTo(self.avatarBgView).offset(6);
        make.height.width.mas_equalTo(33);
    }];

    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.avatarBgView).offset(10);
        make.left.mas_equalTo(self.avatar.mas_right).offset(5);
        make.right.mas_equalTo(self.avatarBgView).offset(-22);
        make.height.mas_equalTo(11);

    }];

    [self.watchLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleLabel);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(4.5);
        make.right.mas_equalTo(self.avatarBgView).offset(-22);
        make.height.mas_equalTo(10);
    }];
    
    
    self.startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.startBtn setTitle:@"开始直播" forState:UIControlStateNormal];
    [self.startBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.startBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    self.startBtn.layer.cornerRadius = 22;
    self.startBtn.clipsToBounds = YES;
    self.startBtn.backgroundColor = rgba(0, 145, 255, 1);
    [self.startBtn addTarget:self action:@selector(startLiveAction) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:self.startBtn];
    
    [self.startBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.width.offset(240);
        make.bottom.mas_equalTo(bgView).offset(-20);
        make.centerX.mas_equalTo(bgView);
    }];
    
    UIView *danView = [[UIView alloc] init];
    danView.backgroundColor = rgba(0, 0, 0, 0.99);
    danView.layer.cornerRadius = 15;
    [bgView addSubview:danView];
    [danView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(bgView).offset(40);
        make.centerY.mas_equalTo(self.startBtn);
        make.height.offset(30);
//        make.width.offset(100);
    }];
   
    CustomSwitch *customSwitch = [[CustomSwitch alloc] init];
    customSwitch.delegate = self;
    [danView addSubview:customSwitch];
    [customSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(danView.mas_left).offset(5);
        make.height.offset(20);
        make.width.offset(35);
        make.centerY.mas_equalTo(danView);
    }];
    
    UILabel *danLabel = [[UILabel alloc] init];
    danLabel.backgroundColor = [UIColor lightGrayColor];
    [danView addSubview:danLabel];
    [danLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(customSwitch.mas_right).offset(8);
        make.centerY.mas_equalTo(danView);
        make.height.offset(16);
        make.width.offset(1);
    }];
    
    UIButton *sayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sayBtn setTitle:@"说些什么~" forState:UIControlStateNormal];
    [sayBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    sayBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [sayBtn addTarget:self action:@selector(sayBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [danView addSubview:sayBtn];
   
    [sayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(danLabel.mas_right).offset(8);
        make.centerY.mas_equalTo(danView);
        make.right.mas_equalTo(danView.mas_right).offset(-10);
    }];
    
    
    
    self.chatTable = [LiveChatViewController new];
    self.chatTable.vcdelegate = self;
    [self addChildViewController:self.chatTable];
    [bgView addSubview:self.chatTable.view];
//    self.chatTable.view.backgroundColor = [UIColor orangeColor];
    [self.chatTable didMoveToParentViewController:self];
    
    [self.chatTable.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(danView);
        make.bottom.mas_equalTo(danView.mas_top).offset(-15);
        make.width.offset(270);
        make.top.mas_equalTo(self.avatarBgView.mas_bottom).offset(15);
    }];
    
    self.chatInputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH)];
    self.chatInputView.backgroundColor = [UIColor clearColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMessageAction)];
    [self.chatInputView addGestureRecognizer:tap];
    self.chatInputView.hidden = true;
    [self.view addSubview:self.chatInputView];
    
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH-70, SCREEN_HEIGHT, 150)];
    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    view.backgroundColor = rgba(245, 246, 250, 1);
    [self.chatInputView addSubview:view];
    
    self.chatTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, SCREEN_WIDTH-50,SCREEN_HEIGHT-5-70-5 , 28)];
    self.chatTextView.font = [UIFont systemFontOfSize:14];
    self.chatTextView.delegate = self;
    [self.chatInputView addSubview:self.chatTextView];
    
    self.sendbutton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectMake(SCREEN_HEIGHT-70, SCREEN_WIDTH-50, 55, 28) image:nil title:@"发送" font:[UIFont systemFontOfSize:13] backColot:rgba(25, 148, 255, 1) textColor:[UIColor whiteColor] target:self action:@selector(sendMessage) layer:3];
    [self.chatInputView addSubview:self.sendbutton];
    
    
    [bgView layoutIfNeeded];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(bgView);
        make.bottom.mas_equalTo(bgView).offset(70);
        make.height.offset(70);
    }];
    self.bottomView.hidden = YES;
}


#pragma mark - 预览视频
- (void)previewVideo{
    // 这里是摄像头可以使用的处理逻辑
    self.manager = [YouinRTCManager shardManager];
    
    // 遵循代理YouinRTCDelegate
    self.manager.delegate = self;
    self.manager.chatDelegate = self;
    // 主播端
    self.manager.modouleFunc = YouinModuleFuncLive;
    // 将预览界面放在View上
    if(self.quality!=3){
                
        [self.manager __init_qiniu_config_Landscape:self.quality == 0?WOOVideoQualityLow:(self.quality==1?WOOVideoQualityMedium:WOOVideoQualityHigh) withView:bgView];
    }else{
        [self.manager __init_qiniu_config_withVideoWidth:self.videoWidth videoHeight:self.videoHeight videokbps:self.videoKb withView:bgView];
    }
    
            
    // 使用前置摄像头采集
    self.manager.captureDevicePosition = AVCaptureDevicePositionFront;
    // 开启美颜
    [self.manager setBeautifyModeOn:YES];

    // 加入指定房间
//    [[YouinRTCManager shardManager] joinRoom:@"1111" callback:^(BOOL success, NSError * _Nullable error) {
//        // 判断一下是否有错误，否则会导致SDK运行不成功
//        if(success){
////            [[ZXMessageCase shareInstace] showHud:@"进入房间..."];
//        }
//    }];
}


- (void)YouinMediaStreamingSession:(PLMediaStreamingSession *)session streamStateDidChange:(PLStreamState)state
{
    switch (state) {
        case PLStreamStateConnected:
        {
            NSLog(@"连接成功");
            [[ZXMessageCase shareInstace] showMessage:@"房间已连接"];
            break;
        }
        case PLStreamStateAutoReconnecting:{
            [[ZXMessageCase shareInstace] showMessage:@"重新连接中"];
            break;
        }
        case PLStreamStateDisconnected:{
            
            [[ZXMessageCase shareInstace] showMessage:@"断开连接"];
            break;
        }

        default:
            break;
    }
}

//    重连后失败
- (void)YouinMediaStreamingSession:(PLMediaStreamingSession *)session didDisconnectWithError:(NSError *)error
{
    __weak typeof(self) weakSelf = self;
    self.heatBeat =  [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        self->_reConnectTime++;
        
        if (self->_reConnectTime >= 4) {
            if (weakSelf.heatBeat) {
                [weakSelf.heatBeat invalidate];
                weakSelf.heatBeat = nil;
            }
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"当前网络不佳被迫退出直播间" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //确定退出
                [self quitRoom:false];
            }];
            [alert addAction:actionConfirm];
            [self presentViewController:alert animated:YES completion:nil];
            return;
        }
        //用重连间隔加倍的方式
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self->_reConnectTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //重启两次
//            NSLog(@"_retryCount22==%d",self->_retryCount);
            NSLog(@"_reConnectTime22==%d",self->_reConnectTime);

         });
         
         
    }];
    [[NSRunLoop currentRunLoop] addTimer:_heatBeat forMode:NSRunLoopCommonModes];
}
   
- (void)alertViewWithMessage{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否要快速重连" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self startReading];
//        });
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //快速重连
            [self.manager.session restartStreamingWithFeedback:^(PLStreamStartStateFeedback feedback) {
                NSLog(@"PLStreamStartStateSuccess--");
            }];
        });
    }];
    [alertVc addAction:cancelAction];
    [alertVc addAction:sureAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}
- (void)startTimer {
    
    if (self.roomStateTimer == nil)
    {
        self.roomStateTimer = [NSTimer timerWithTimeInterval:1.0
                                                      target:self
                                                    selector:@selector(timerTimeout)
                                                    userInfo:nil
                                                     repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.roomStateTimer forMode:NSRunLoopCommonModes];
    }
    //alloc要加上
//    [self.roomStateTimer setFireDate:[NSDate distantPast]];
}

- (void)timerTimeout {
    
    self.roomStateSeconds--;
    if (self.roomStateSeconds == 0) {
        
        [self stopTimer];
        [RYAlertController showAlertWithTitle:@"" message:@"当前网络不佳被迫退出直播间" appearanceProcess:^(RYAlertController * _Nonnull alertMaker) {
            alertMaker.addActionDefaultTitle(@"确定");
        } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, RYAlertController * _Nonnull alertSelf) {
            [self quitRoom:false];
        }];
    }
    
}


- (void)stopTimer {
    if(self.roomStateTimer!=nil){
        [self.roomStateTimer invalidate];
        self.roomStateTimer = nil;
        self.roomStateSeconds = 30;
    }
}


- (void)quitRoom:(BOOL)isStop
{
    appDelegate.isFlip = false;
    [self.manager.session stopStreaming];
    [self.manager stopLive:isStop withRoomId:self.roomId suc:^(id  _Nonnull json) {
        
    } failure:^(id  _Nonnull error) {
        
    }];
    [self.manager leaveRoom];
   
    [self.navigationController popViewControllerAnimated:YES];
  
}

#pragma mark - 弹幕开关
- (void)switchWithSelected:(BOOL)isSelected
{
    self.chatTable.view.hidden = isSelected;
}

#pragma mark - 开始直播
- (void)startLiveAction
{
    if(self.publishUrl.length==0){
        [[ZXMessageCase shareInstace] showMessage:@"请输入推流地址"];
        return;
    }
    
    [self.manager.session startStreamingWithPushURL:[NSURL URLWithString:self.publishUrl] feedback:^(PLStreamStartStateFeedback feedback) {
                        
            if (feedback == PLStreamStartStateSuccess) {
                NSLog(@"Streaming started.");
                [[ZXMessageCase shareInstace] showMessage:@"直播开始了"];
                self.startBtn.hidden = YES;
                self.isLive = true;
                self.tap.hidden = NO;
            } else if (feedback == PLStreamStartStateStreamURLUnauthorized) {
                [[ZXMessageCase shareInstace] showMessage:@"当前的 流地址 没有被授权"];
            }else if (feedback == PLStreamStartStateSessionPushURLInvalid) {
                [[ZXMessageCase shareInstace] showMessage:@"当前的 推流地址 没有被授权"];
            }else{
                [[ZXMessageCase shareInstace] showMessage:@"发现未知错误，请联系客服"];
            }
        }];
}

#pragma mark - 点击屏幕
- (void)tapAction:(UIButton *)sender
{
    self.bottomView.hidden = NO;
    sender.selected = !sender.selected;
    [UIView animateWithDuration:0.3 animations:^{
        [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self->bgView);
            make.height.offset(70);
            
            if(sender.selected){
                make.bottom.mas_equalTo(self->bgView);//显示
            }else{
                make.bottom.mas_equalTo(self->bgView).offset(70);//退出屏幕外
            }
            
        }];
        [self->bgView layoutIfNeeded];
    }];

}
#pragma mark - 输入内容
- (void)sayBtnAction
{
    self.chatInputView.hidden = false;
    [self.chatTextView becomeFirstResponder];
}
-(void)sendMessage{
    if([self.chatTextView.text isEqualToString:@""]){
        [[ZXMessageCase shareInstace] showMessage:@"不能发送空消息"];
        return;
    }
    [self.manager sendTextMessage:self.chatTextView.text callback:nil];
    self.chatTextView.text = @"";
    [self.chatTextView resignFirstResponder];
}
-(void)tapMessageAction{
    [self.chatInputView endEditing:YES];
    [UIView animateWithDuration:0.3 animations:^{
        self.chatInputView.frame = CGRectMake(0, 200, SCREEN_HEIGHT, SCREEN_WIDTH);
    } completion:^(BOOL finished) {
        self.chatInputView.hidden = true;
        self.chatInputView.frame = CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
    }];
}


#pragma mark - 结束直播&&离开直播
- (void)bottomActionWithTag:(NSInteger)tag
{
    if(self.isLive){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:tag==100?@"确认关闭直播间吗?":@"确认离开直播间吗?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
            if([self.delegate respondsToSelector:@selector(LandscapeLiveIsStoped:)])
            {
                [self.delegate LandscapeLiveIsStoped:tag==100?true:false];
            }
            [self quitRoom:tag==100?true:false];
        }];
        UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

        [alert addAction:okAction];
        [alert addAction:cancelAction];

        // 弹出对话框
        [self presentViewController:alert animated:true completion:nil];
    }else{
        appDelegate.isFlip = false;
        [self.chatTable.view setHidden:true];
        [self.manager leaveRoom];
        [self.navigationController popViewControllerAnimated:YES];
    }
   
}

#pragma mark - 美观，开关麦
- (void)bottomVideoActions:(NSInteger)tag withButton:(UIButton *)sender
{
    if(tag == 200){//开关麦
        sender.selected = !sender.selected;
        if(sender.selected){
            [self.manager muteMicrophone:YES];
            [[ZXMessageCase shareInstace] showMessage:@"关闭麦克风"];
        }else{
            [self.manager muteMicrophone:NO];
            [[ZXMessageCase shareInstace] showMessage:@"打开麦克风"];
        }
    
    }else if (tag == 201){
        sender.selected = !sender.selected;
        if(sender.selected){
            [self.manager setBeautifyModeOn:NO];
            
            [[ZXMessageCase shareInstace] showMessage:@"关闭美颜"];
        }else{
            [self.manager setBeautifyModeOn:YES];
            [[ZXMessageCase shareInstace] showMessage:@"打开美颜"];
        }
    }else{
        [self.manager changeCamera];
    }
}


- (void)getRoomIdWithPulishUrl:(NSString *)url
{
        NSString *prefix = @"";
        NSRange range = [url rangeOfString:@"course"];
       if (range.location != NSNotFound) {
           prefix = @"course";
       }else{
           prefix = @"live";
       }
    
        NSRange prefixRange = [url rangeOfString:[prefix isEqualToString:@"course"]?@"course":@"live"];
        
        if (prefixRange.location != NSNotFound) {
            NSInteger start = prefixRange.location + prefixRange.length;
            
            NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
            NSRange digitsRange = [url rangeOfCharacterFromSet:nonDigitCharacterSet options:NSNumericSearch range:NSMakeRange(start, url.length - start)];
            
            if (digitsRange.location != NSNotFound) {
                NSInteger end = digitsRange.location;
                NSString *numberString = [url substringWithRange:NSMakeRange(start, end - start)];
                
                NSLog(@"Extracted number: %@", numberString);
                self.roomId = numberString;
                //获取直播间消息
                [self.manager getCourseinfo:self.roomId];
                [self.manager getRoomStatus:self.roomId];
            } else {
                NSLog(@"No number found after 'course'.");
            }
        } else {
            NSLog(@"'course' prefix not found in the URL.");
        }
}


-  (void)courseInfo:(CourseModel *)courseInfoModel error:(NSError *)error
{
    if(courseInfoModel){
        self.corseInfoModel = courseInfoModel;
        // 获取历史消息
        [[YouinRTCManager shardManager] getHistoryMessage:100 callback:^(NSArray<BaseMessageModel *> * _Nonnull message, NSError * _Nullable error) {
            // messageType -1  文字信息  -2 图片信息
            for(BaseMessageModel *i in message){
                i.color = rgba(arc4random() % 256, arc4random() % 256, arc4random() % 256, 1);
            }
            
            [self.chatTable.messageArray addObjectsFromArray:message];
            self.chatTable.messageArray = [NSMutableArray arrayWithArray:[[self.chatTable.messageArray reverseObjectEnumerator] allObjects]];
            [self.chatTable.tableView reloadData];
            [self.chatTable.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        }];
    }
}
- (void)enterpriseInfo:(EnterpriseModel *)enterpriseModel error:(NSError *)error
{
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:enterpriseModel.frontend_logo]];
    self.titleLabel.text = enterpriseModel.org_name;
}
- (void)statusInfo:(StatusModel *)statusModel error:(NSError *)error
{
    self.watchLabel.text = [NSString stringWithFormat:@"%d次访问",statusModel.pv_count];
}
#pragma mark - 收到IM消息
-(void)onNewMessageRecive:(BaseMessageModel *)messageModel{
    
    if([messageModel.ws_type isEqualToString:@"newUserJoinRoom"]){

        // 记录进入时间
        NSTimeInterval enterTime = [[NSDate date] timeIntervalSince1970];
        [self.enterTimeArray addObject:@(enterTime)];
        [self.enterNameArray addObject:messageModel.nickName];

        
        // 创建进入提示视图
        EnterTipView *tipView = [[EnterTipView alloc] initWithFrame:CGRectMake(0,SCREEN_HEIGHT, SCREEN_WIDTH-30, 40)];
        [tipView.btnTitle setTitle:[NSString stringWithFormat:@"%@ 进入了直播间",messageModel.nickName] forState:0];
        CGSize size = [tipView.btnTitle.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: tipView.btnTitle.titleLabel.font}];
        CGFloat width = size.width;
        // 设置进入提示视图的宽度
        CGRect frame = tipView.frame;
        frame.size.width = width + 40.0; // 加上左右边距
        tipView.frame = frame;
        
        // 将进入提示视图添加到父视图中
        [self.view addSubview:tipView];
        // 将进入提示视图保存到数组中，以便后续排序
        [self.enterTipViews addObject:tipView];

        // 动画显示进入提示视图
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = tipView.frame;
            frame.origin.y = self.chatTable.view.frame.origin.y+self.enterTipViews.count * 30;
            tipView.frame = frame;
        } completion:^(BOOL finished) {
            // 动画完成后，延迟一定时间后隐藏进入提示视图
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:0.3 animations:^{
                    CGRect frame = tipView.frame;
                    frame.origin.x = -SCREEN_WIDTH;
                    tipView.frame = frame;
                } completion:^(BOOL finished) {
                    // 动画完成后，从父视图中移除进入提示视图
                    [tipView removeFromSuperview];
                    [self.enterTipViews removeObject:tipView];
                }];
            });
        }];
        
        
        [self sortEnterTipsByTime];
    }
    else{
        // messageType -1  文字信息  -2 图片信息
        messageModel.color = rgba(arc4random() % 256, arc4random() % 256, arc4random() % 256, 1);
        [self.chatTable.messageArray insertObject:messageModel atIndex:0];
//        [self.chatTable refreshGift];
        [self.chatTable.tableView reloadData];
        [self.chatTable.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];

        if(messageModel.isGift){
            // 礼物消息

        }
    }

}

- (void)sortEnterTipsByTime {
    // 先移除超过5个的进入提示视图
    if (self.enterTipViews.count > 5) {
        NSInteger removeCount = self.enterTipViews.count - 5;
        for (NSInteger i = 0; i < removeCount; i++) {
            EnterTipView *tipView = self.enterTipViews[i];
            [tipView removeFromSuperview];
        }
        [self.enterTipViews removeObjectsInRange:NSMakeRange(0, removeCount)];
    }

    // 根据进入时间戳排序
    NSArray *sortedArray = [self.enterTimeArray sortedArrayUsingComparator:^NSComparisonResult(NSNumber *obj1, NSNumber *obj2) {
        NSTimeInterval time1 = [obj1 doubleValue];
        NSTimeInterval time2 = [obj2 doubleValue];
        return time1 - time2;
    }];

    // 重新排列进入提示视图的位置
    for (NSInteger i = 0; i < sortedArray.count; i++) {
        NSTimeInterval enterTime = [sortedArray[i] doubleValue];
        NSInteger index = [self.enterTimeArray indexOfObject:@(enterTime)];
        if (index != NSNotFound && index < self.enterTipViews.count) {
            EnterTipView *tipView = self.enterTipViews[index];
            CGRect frame = tipView.frame;
            frame.origin.y = self.chatTable.view.frame.origin.y + i * 30;
            tipView.frame = frame;
        }
    }

    // 如果当前屏幕上显示的进入提示视图数量超过了5个，则移除多余的进入提示视图
    if (self.enterTipViews.count > 5) {
//        NSInteger removeCount = self.enterTipViews.count - 5;
        for (NSInteger i = self.enterTipViews.count - 1; i >= 5; i--) {
            EnterTipView *tipView = self.enterTipViews[i];
            [UIView animateWithDuration:0.3 animations:^{
                CGRect frame = tipView.frame;
                frame.origin.x = -SCREEN_WIDTH;
                tipView.frame = frame;
            } completion:^(BOOL finished) {
                [tipView removeFromSuperview];
                [self.enterTipViews removeObjectAtIndex:i];
            }];
        }
    }
}
-(long )cTimestampFromString:(NSString *)theTime {
    // theTime __@"%04d-%02d-%02d %02d:%02d:00"
    // 转换为时间戳
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    // NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    // [formatter setTimeZone:timeZone];
    NSDate* dateTodo = [formatter dateFromString:theTime];
    return  (long)[dateTodo timeIntervalSince1970];
   
}

- (BottomActionView *)bottomView
{
    if(!_bottomView){
        _bottomView = [[BottomActionView alloc] init];
        _bottomView.delegate = self;
        [bgView addSubview:_bottomView];
    }
    return _bottomView;
}
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
//    return UIInterfaceOrientationMaskLandscape;
//}
//- (BOOL)shouldAutorotate {
//    return YES;
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
